#coding:utf-8

# --------------------------------------------------------------------------------
# 上岗持证要求的管理
# --------------------------------------------------------------------------------
module PaperRequireService
  def self.registered(app)

    app.get "/?" do
      PaperRequireDomain.all.to_json
    end
    
    app.get "/:id" do
      param :id, Integer, required: true
      
      elem =  PaperRequireRepo[params[:id]]
      elem.nil? ? raise("not found paper require: #{params[:id]}") : elem.perfect.to_json
    end

    app.post "/?" do
      param :manager_id,     Integer,  required: true
      param :position_id,    String,   required: true
      param :paper_type_ids, Array,    required: true, min_length: 1   # 不能少于一项
      
      PaperRequireDomain.create(params.symbolize_keys).to_json
    end

    app.put "/:id/?" do
      param :id,   Integer, required: true
      param :manager_id,       Integer,  required: false
      param :position_Id,      String,   required: false
      param :paper_type_id,    Integer,  required: false
      
      elem = PaperRequireRepo[params[:id]]
      valid_params = params.keep_if{|k,v| %w(manager_id position_id paper_type_id).include?(k)}.symbolize_keys
      if elem
        new_elem = elem.update(valid_params)
        (new_elem ? new_elem.save : elem).perfect.to_json
      end
    end

    app.delete "/:id/?" do
      param :id, Integer, required: true
      
      elem = PaperRequireRepo[params[:id]]
      if elem
        begin
          elem.delete
          {result: :ok, id: elem.id}.to_json
        rescue SQLite3::ConstraintException
          {result: :error, message: "delete paper require failed, id: #{elem.id}"}.to_json
        end
      else
        {result: :error, message: "delete paper require failed, not found id: #{params[:id]}"}.to_json
      end
    end
  end
end
